import string
import serial
import time
import numpy as np
import pandas as pd
from datetime import datetime
import json
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

name_of_txt = 'current2'
with open(fr"current\{name_of_txt}.txt","r") as f:
    data = f.read()
    # print(data)
    print(type(data))
    a = data.split()
    print(a)
current_list=[]

count = len(a)
print(count)
for i in range(0, count-1, 2):
    current = int(a[i],16)*256 + int(a[i+1],16)
    if(current >= 32768):
        current = current - 65536
    # if(current >= 1000 or current <=-1000):
    #     current = 0
    current_list.append(current)


def divide_into_parts(lst,num):
    total_length = len(lst)
    part_size = total_length // num  # 每份的大小
    remainder = total_length % num  # 剩余的元素数量

    # 初始化一个列表来存储分割后的结果
    divided_parts = []

    # 计算每份的起始和结束索引
    for i in range(num):
        start_index = i * part_size + min(i, remainder)
        end_index = start_index + part_size + (1 if i < remainder else 0)

        # 将每份添加到结果列表中
        divided_parts.append(lst[start_index:end_index])

    return divided_parts

parts_24=divide_into_parts(current_list,24)


def remove_outliers(region_data, lower, upper):
    # 计算区域的百分位数
    lower_limit = np.percentile(region_data, lower)
    upper_limit = np.percentile(region_data, upper)
    print(lower_limit, upper_limit)
    length = len(region_data)
    region_data1 = [0 for i in range(length)]
    for i in range(len(region_data)):
        if (region_data[i] >= upper_limit or region_data[i] <= lower_limit):
            if(i>=64):
                region_data1[i] = region_data[i - 64]
            elif( i<=1 or i>=length-2):
                region_data1[i] =  np.mean(region_data)
            else:
                region_data1[i] = 0.5 * (region_data[i - 1] + region_data[i + 1])
        else:
            region_data1[i] = region_data[i]
    return region_data1

def remove_outliers1(region_data, lower, upper):
    # 计算区域的百分位数
    lower_limit = np.percentile(region_data, lower)
    upper_limit = np.percentile(region_data, upper)
    print(lower_limit, upper_limit)
    length = len(region_data)
    region_data1 = [0 for i in range(length)]
    for i in range(len(region_data)):
        if (region_data[i] >= upper_limit or region_data[i] <= lower_limit):
            if( i<=1 or i>=length-2):
                region_data1[i] = np.mean(region_data)
            else:
                region_data1[i] = 0.5 * (region_data[i - 1] + region_data[i + 1])
        else:
            region_data1[i] = region_data[i]
    return region_data1

def remove_outliers2(region_data, lower, upper):
    # 计算区域的百分位数
    lower_limit = lower
    upper_limit = upper
    print(lower_limit, upper_limit)
    length = len(region_data)
    region_data1 = [0 for i in range(length)]
    for i in range(len(region_data)):
        if (region_data[i] >= upper_limit or region_data[i] <= lower_limit):
            region_data1[i] = 0
        else:
            region_data1[i] = region_data[i]
    return region_data1

current_list1 = []


for part in parts_24:
    part1 = remove_outliers(part,0.5,99.5)
    part2 = remove_outliers(part1,0.05,99.95)
    part3 = remove_outliers2(part2,-1000,1000)
    current_list1.extend(part3)

# print(current_list)
ave = np.mean(current_list1)
current_list2 = [x-ave for x in current_list1]
length = len(current_list2)
error_list=[current_list[i]-current_list1[i] for i in range(length)]

t = range(len(current_list))
fig=plt.figure(figsize=(5,4))
plt.title('测量数据暂态变化曲线')  # 设置标题
# plt.plot(t,current_list,alpha = 0.5,marker='o',markersize=5)
plt.plot(t,current_list2)
# plt.plot(t,error_list)
plt.show()
dic0 = dict(zip(t,current_list))
# dic3 = dict(zip(t,current_list1))
dic1 = dict(zip(t,current_list2))
dic2 = dict(zip(t,error_list))
# write_dict('test.txt',dic1)
# dic2 = read_dict('data_of_kettle.txt')
series0 = pd.Series(dic0)
series1 = pd.Series(dic1)
series2 = pd.Series(dic2)
# series3 = pd.Series(dic3)

# series1.to_csv('test62_0.csv')
# series2.to_csv('error_test62_0.csv')

d = {'before':series0,'after':series1,'error':series2}
df = pd.DataFrame(d)

# df.to_csv(fr'{name_of_txt}_{datetime.now().strftime("%m_%d_%H_%M_%S")}.csv')
df.to_csv(fr'{name_of_txt}.csv')
# series1.to_csv(f'test{int(1000*time.time())}.csv')